package com.semanticweb.webapp.security;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.semanticweb.webapp.service.RBACService;

public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private RBACService rbacService;

    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        LOGGER.error("krecem da trazim po uname - " + username);
        LOGGER.error("trenutni rbac service - " + rbacService);
        final UserInSession userFromDB = fetchFromService(username);
        LOGGER.error("User fetched from service - " + userFromDB);
        return new User(userFromDB.getUserName(), userFromDB.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(userFromDB.getRoles()));
    }

    private UserInSession fetchFromService(final String username) {
        final com.semanticweb.webapp.model.rbac.User user = rbacService.getUser(username);
        UserInSession inSession = null;
        if (user != null) {
            inSession = new UserInSession();
            inSession.setUserName(user.getUsername());
            inSession.setPassword(user.getPassword());
        	LOGGER.error("inSession username - " + (inSession.getUserName()));
        	LOGGER.error("inSession password - " + (inSession.getPassword()));
            String roles = "";
            List<String> userRoles = rbacService.getRoleNamesForUser(user.getUsername());
            LOGGER.error("user roles - " + (userRoles.size()));
            // final Iterator<Role> roleIt = user.getRoles().iterator();
            for (final String roleName : userRoles) {
                roles += ", ROLE_" + roleName;
            }
            if (roles.length() > 0) {
                roles = roles.substring(2);
            }
            inSession.setRoles(roles);
            LOGGER.error("roles from service: " + roles);
        }
        return inSession;
    }
}